package com.example.tuter.activity;

import static com.example.tuter.util.ImageUploadHelper.CHOOSE_PHOTO;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.tuter.R;
import com.example.tuter.activity.util.PageResultHandler;
import com.example.tuter.activity.util.PageResultHelper;
import com.example.tuter.activity.util.SendPhotoActivity;
import com.example.tuter.adapter.FloorInfoAdapter;
import com.example.tuter.entity.Floor;
import com.example.tuter.entity.Message;
import com.example.tuter.entity.PageResult;
import com.example.tuter.entity.Post;
import com.example.tuter.util.Constant;
import com.example.tuter.util.ImageUploadHelper;
import com.example.tuter.util.UpdateUIUtil;
import com.example.tuter.util.httpUtil.HttpCodeConstant;
import com.example.tuter.util.httpUtil.HttpFunction.CommunityAPI;
import com.example.tuter.util.httpUtil.HttpFunction.UserAPI;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//查看post内具体内容
public class ViewPostActivity extends BaseActivity implements PageResultHandler<Floor>, SendPhotoActivity {
    String TAG = ViewPostActivity.class.getSimpleName();


    private boolean isCollect = false;

    private final PageResultHelper<Floor> pageHelper = new PageResultHelper<Floor>();

    //存储传输过来的post
    Post post;

    ImageUploadHelper util;

    private FloorInfoAdapter floorsInfoAdapter;

    private CommunityAPI communityAPI;
    private EditText editText;
    private ImageView imageView_subs;
    private SwipeRefreshLayout swipeRefreshLayout;
    private UserAPI userAPI;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    private void checkCollect() {
        Call<Message<String>> call = userAPI.isStar(post.getPid());
        call.enqueue(new Callback<Message<String>>() {
            @Override
            public void onResponse(Call<Message<String>> call, Response<Message<String>> response) {
                Message<String> body = response.body();
                if (body.getCode() == HttpCodeConstant.HAS_STAR.getValue()) {
                    isCollect = true;
                }
                if (!isCollect) {
                    imageView_subs.setImageResource(R.drawable.sc_normal);//未收藏
                } else {
                    imageView_subs.setImageResource(R.drawable.sc_press);//已收藏
                }
            }

            @Override
            public void onFailure(Call<Message<String>> call, Throwable t) {

            }
        });
    }


    //设置点击收藏的函数
    private void setCollect() {
        imageView_subs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //收藏
                doCollect(post.getPid());
            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int RequestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(RequestCode, permissions, grantResults);
        switch (RequestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    util.openAlbum();
                } else {
                    Toast.makeText(this, "you denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onActivityResult(int RequestCode, int ResultCode, Intent data) {
        switch (RequestCode) {
            case CHOOSE_PHOTO:
                if (ResultCode == RESULT_OK) {
                    util.handleImageOnKitKat(data, null);//应该是图片预览按钮
                }
                break;
            default:
                break;
        }
    }


    /**
     * 发出收藏请求
     *
     * @param pid
     */
    public void doCollect(Integer pid) {
        try {

            retrofit2.Call<Message<String>> doCall;
            if (!isCollect) {
                doCall = communityAPI.like(pid);
            } else {
                doCall = communityAPI.unlike(pid);
            }

            doCall.enqueue(new Callback<Message<String>>() {
                @Override
                public void onResponse(retrofit2.Call<Message<String>> call, retrofit2.Response<Message<String>> response) {
                    isCollect = !isCollect;
                    //要更新ui吗？
                    if (isCollect) imageView_subs.setImageResource(R.drawable.sc_press);
                    else imageView_subs.setImageResource(R.drawable.sc_normal);

                }

                @Override
                public void onFailure(retrofit2.Call<Message<String>> call, Throwable t) {
                    Toast.makeText(ViewPostActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public Call<Message<PageResult<Floor>>> getDataByPage(Integer pageNo) {
        return communityAPI.getFloor(post.getPid(), pageNo);
    }

    @Override
    public void updateUI() {
        UpdateUIUtil.updateUIBySingleAdapter(floorsInfoAdapter);
    }



    @Override
    public void sendPhotoContent() {
        try {
            //应该判断一下，不能内容和图片都为空
            Call<Message<Floor>> call = communityAPI.publishFloor(post.getPid(), editText.getText().toString(), util.getUploadImageUri());
            call.enqueue(new Callback<Message<Floor>>() {
                @Override
                public void onResponse(Call<Message<Floor>> call, Response<Message<Floor>> response) {
                    Message<Floor> body = response.body();
                    if(body.getCode()==HttpCodeConstant.SUCCESS.getValue()){
                        //发送成功
                        Toast.makeText(ViewPostActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        pageHelper.add(body.getData());
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        // 隐藏软键盘
                        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                        editText.setText("");
                        updateUI();
                    }else{
                        Toast.makeText(ViewPostActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                    }


                }

                @Override
                public void onFailure(Call<Message<Floor>> call, Throwable t) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        //重新加载floors
        post = (Post) intent.getSerializableExtra("post");
        communityAPI = Constant.r.create(CommunityAPI.class);
        userAPI = Constant.r.create(UserAPI.class);
    }

    @Override
    protected void bindEvent() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //这里有问题，需要改。刷新后会把占位给吞掉。
                pageHelper.getFirstPageInRefreshing(ViewPostActivity.this, swipeRefreshLayout, floorsInfoAdapter);
            }
        });


        //点击楼层进入到具体的楼层中，查看回复
        floorsInfoAdapter.setRecyclerItemClickListener(new FloorInfoAdapter.OnRecyclerItemClickListener() {
            @Override
            public void onRecyclerItemClick(int position) {
                Floor floor = pageHelper.getData().get(position);
                Intent intent = new Intent(ViewPostActivity.this, ViewFloorActivity.class);
                intent.putExtra("floor", floor);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initView() {

        //设置当前布局
        setContentView(R.layout.activity_view_post);
        //设置标题
        final TextView textView_title = (TextView) findViewById(R.id.fragment_tie_toolbar_textView);
        textView_title.setText(post.getTitle());
        editText = findViewById(R.id.fragment_tie_editText_send_comment);


        //图片处理
        ImageView imageView_send = findViewById(R.id.fragment_tie_button_send_comment);
        ImageView imageView_choose_pic = findViewById(R.id.fragment_tie_imageView_choose_pic);
        ImageView imageView_back = findViewById(R.id.fragment_tie_toolbar_imageView);
        util = new ImageUploadHelper(this, this, imageView_send, imageView_choose_pic, imageView_back);


        swipeRefreshLayout = findViewById(R.id.fragment_tie_refresh);
        //楼层展示
        RecyclerView recyclerView = findViewById(R.id.fragment_tie_recyclerView);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        floorsInfoAdapter = new FloorInfoAdapter(post,pageHelper.getData(), this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(floorsInfoAdapter);
        //收藏按钮
        imageView_subs = findViewById(R.id.fragment_tie_toolbar_imageview_sub);
        //检查该贴是否收藏
        if (Constant.userInfo != null) {
            checkCollect();
        }
        //设置收藏图标
        setCollect();


        pageHelper.add(new Floor());
        //设置滑动自动加载
        pageHelper.addPageScroll(this,recyclerView);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_view_post;
    }
}


